package com.community.web.user.custom.interceptor;

import com.community.common.exception.NeusoftException;
import com.community.common.login.LoginUser;
import com.community.common.login.LoginUserHolder;
import com.community.common.result.ResultCodeEnum;
import com.community.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access-token");

        String secretKey = "fUY7Zgwdyl9lWmKwqadOnbLcEnHmeB1F";
        try {
            Claims claims = JwtUtil.parseJWT(secretKey, token);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);

            LoginUserHolder.setLoginUser(new LoginUser(userId, username));

            return true;
        } catch (ExpiredJwtException e) {
            throw new NeusoftException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new NeusoftException(ResultCodeEnum.TOKEN_INVALID);
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
